<template>
  <div class="left_container">
    <el-card
      shadow="always"
      :body-style="{
        padding: '0px 10px',
        height: '80vh',
        width: '18vw',
        overflow: 'auto',
      }"
    >
      <!-- <el-scrollbar style="height: 100%"> -->
      <div class="left_title">
        <i class="el-icon-edit"></i>
        <span>基础组件</span>
      </div>
      <draggable
        :clone="onClone"
        :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
        :sort="false"
        id="components"
        :list="components"
        draggable=".left_item"
        @end="onEnd"
      >
        <div
          v-for="(item, index) in components"
          :key="index"
          @click="add(item)"
          class="left_item"
          :id="index"
        >
          <svg-icon :icon-class="item.type" />
          <span>{{ item.text }}</span>
        </div>
      </draggable>
      <!-- </el-scrollbar> -->
    </el-card>

    <el-card
      style="margin: 0 10px"
      shadow="always"
      :body-style="{
        padding: '20px 7px',
        height: '87vh',
        width: '50vw',
        overflow: 'auto',
      }"
    >
      <el-form :model="{ formList }" ref="form" label-width="0" size="small">
        <!-- <el-scrollbar style="height: 100%; padding: 15px"> -->
        <textarea class="title" type="text" v-model="title"></textarea>

        <draggable
          group="componentsGroup"
          id="form"
          :list="formList"
          animation="200"
          class="draggable_class"
          draggable=".draggable_item"
          ghostClass="ghost"
          @end="onEnd1"
        >
          <item
            v-for="(item, index) in formList"
            :node="item"
            :index="index"
            :key="'item_' + index"
            @currentNode="currentNode"
            @deleteNode="deleteNode"
            @Node="Node"
            @save="sort()"
          ></item>
          <div style="100px">&nbsp;</div>
        </draggable>

        <!-- </el-scrollbar> -->
      </el-form>
    </el-card>

    <el-card
      shadow="always"
      :body-style="{
        padding: '10px 3px',
        height: '76vh',
        width: '28vw',
        overflow: 'auto',
      }"
    >
      <span slot="header">
        <el-button type="text" icon="el-icon-upload" @click="save()"
          >保存</el-button
        >
        <span v-if="save_time" style="float: right; padding: 12px 0">{{
          save_time + "保存"
        }}</span>
      </span>
      <!-- <el-scrollbar style="height: 93%"> -->
      <el-form
        style="padding: 10px; padding-right: 20px"
        label-position="left"
        :model="node"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <setting v-if="node" :node="node"></setting>
      </el-form>
      <!-- </el-scrollbar> -->
    </el-card>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import item from "./item.vue";
import setting from "./setting.vue";
import { save, update, getSurvey } from "@/api/form";
import { debounce } from "@/utils/index";
import md5 from "js-md5";
const defaut_question = {
  num: 0,
  type: null,
  title: "标题",
  id: 0,
  span: 24,
  require: true,
  answer: null,
  show: true,
  tip: null,
};
export default {
  components: {
    draggable,
    item,
    setting,
  },
  data() {
    return {
      components: [
        {
          type: "1",
          text: "单行文本",
        },
        {
          type: "2",
          text: "多行文本",
        },
        {
          type: "3",
          text: "单选框组",
        },
        {
          type: "4",
          text: "多选框组",
        },
        {
          type: "5",
          text: "日期时间",
        },
        {
          type: "6",
          text: "图片上传",
        },
        {
          type: "7",
          text: "省市级联",
        },
        {
          type: "8",
          text: "文件上传",
        },
        {
          type: "9",
          text: "手写签名",
        },
        {
          type: "10",
          text: "地理位置",
        },
        {
          type: "11",
          text: "横向填空",
        },
      ],
      formList: [],
      node: null,
      id: 25,
      title: "问卷标题",
      save_time: null,
      logicList: [],
      currentMD5: null,
    };
  },
  created() {
    this.debounceInit = debounce(100, this.check);
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getForm();
    }
    setInterval(() => {
      this.save();
    }, 10000);
  },
  beforeRouteLeave(to, from, next) {
    const loading = this.$loading({
      lock: true,
      text: "保存中....",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    this.save().then((res) => {
      next();
      loading.close();
    });
  },
  methods: {
    check(e) {
      let logicList = e[0];
      let formList = e[1];
      for (let j = 0; j < logicList.length; j++) {
        const l = logicList[j];
        let t = 0;
        for (let i = 0; i < l.list.length; i++) {
          const a = l.list[i];
          let target = formList[formList.map((item) => item.id).indexOf(a.id)];
          if (a.type == 0) {
            if (target.answer == a.answer) t++;
          } else {
            if (target.answer != a.answer) t++;
          }
        }
        let index = formList.map((item) => item.id).indexOf(parseInt(l.id));
        if (l.type == 0) {
          t >= l.list.length
            ? formList[index].show == true
              ? null
              : this.$set(formList[index], "show", true)
            : formList[index].show == false
            ? null
            : this.$set(formList[index], "show", false);
        } else {
          t > 0
            ? formList[index].show == true
              ? null
              : this.$set(formList[index], "show", true)
            : formList[index].show == false
            ? null
            : this.$set(formList[index], "show", false);
        }
      }
    },
    Node(e) {
      return this.node;
    },
    currentNode(e) {
      this.node = e;
      this.formList.length == 0 ? (this.node = null) : null;
    },
    deleteNode(e) {
      if (this.formList.indexOf(e) !== -1) {
        this.formList.splice(this.formList.indexOf(e), 1);
        this.sort();
      }
      this.formList.length == 0 ? (this.node = null) : null;
    },
    add(item) {
      let o = JSON.parse(JSON.stringify(defaut_question));
      o.id += new Date().getTime();
      o.type = item.type;
      o.title = item.text;
      o.num = this.formList.length + 1;
      this.formList.push(o);
    },
    onClone(e) {
      let o = JSON.parse(JSON.stringify(defaut_question));
      o.id = new Date().getTime();
      o.type = e.type;
      o.title = e.text;
      return o;
    },
    onEnd(e) {
      if (e.to != e.from) {
        this.sort();
      }
    },
    onEnd1(e) {
      if (e.to == e.from) {
        this.sort();
      }
    },
    sort() {
      for (let i = 0; i < this.formList.length; i++) {
        let e = this.formList[i];
        e.num = i + 1;
      }
    },
    async save() {
      let m = md5(JSON.stringify(this.formList));
      m = md5(m + this.title);

      if (m != this.currentMD5) {
        const [err, data] = await update(this.id, {
          text: JSON.stringify(this.formList),
          logic: JSON.stringify(this.logicList),
          title: this.title,
        })
          .then((res) => [null, res])
          .catch((err) => [err, null]);
        if (err) {
          this.$notify({
            title: "提示",
            message: "保存问卷是失败",
            type: "error",
            duration: "2000",
            position: "top-right",
            showClose: "true",
          });
          return;
        }

        this.currentMD5 = m;
        this.save_time = new Date().toLocaleString();

        this.$notify({
          title: "提示",
          message: "保存问卷成功",
          type: "success",
          duration: "2000",
          position: "top-right",
          showClose: "true",
        });
      }
    },

    getForm() {
      getSurvey(this.id).then((res) => {
        let formList = JSON.parse(res.text);
        let logicList = JSON.parse(res.logic);
        formList.map((i) => (i.show = true));

        this.currentMD5 = md5(res.text);
        this.currentMD5 = md5(this.currentMD5 + res.title);
        this.title = res.title;

        this.check([logicList, formList]);

        this.formList = formList;
        this.logicList = logicList;
      });
    },
  },
  watch: {
    formList: {
      handler(n, o) {
        this.debounceInit
          ? this.debounceInit(this.logicList, this.formList)
          : null;
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
.el-card {
  height: 84vh;
}
.title {
  font-size: 23px;
  outline: none;
  text-align: center;
  width: 100%;
  border: none;
}
.title:focus {
  border: 1px dashed gray;
  height: 100px;
}
#form .left_item {
  width: 100%;
  overflow: hidden;
  border-top: #409eff solid 5px;
  line-height: 100px;
  text-indent: -9999px;
}
#form >>> .ghost {
  border-top: #409eff solid 5px;
}
.left_container {
  display: flex;
}
.left_container >>> .el-scrollbar__wrap {
  height: 100%;
  overflow-x: hidden;
}
.left_container >>> .el-scrollbar__wrap::-webkit-scrollbar {
  display: none;
}
.left_container >>> .el-card__body::-webkit-scrollbar {
  display: none;
}
.left_container >>> .el-scrollbar__view {
  height: 100%;
}

.left_title {
  padding: 10px 10px;
}

#components .left_item {
  width: 48%;
  padding: 7px 0;
  padding-left: 10px;
  margin: 1%;
  border-radius: 3px;
  cursor: move;
  border: 1px dashed #fff;
  float: left;
  font-size: 12px;
  background: #f3f9ff;
}

#components .left_item:hover {
  border: 1px dashed #409eff;
  color: #409eff;
}

#form {
  height: 100%;
}
.el-form {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}
.left_item >>> .svg-icon {
  width: 1.2rem;
  height: 1rem;
}
.left_container >>> .el-card__header {
  padding: 10px;
}

::-webkit-scrollbar {
  width: 5px;
  height: 10px;
}
::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: #409eff;
}
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #ededed;
  border-radius: 5px;
}
</style>
